from django.shortcuts import render
from .models import UserInfo
from django.http import HttpResponse
from django.views.generic import View
from django.utils.decorators import method_decorator

# Create your views here.
#注册类
class RegisterView(View):
    #处理get请求
    def get(self,request):
        return render(request,'./register.html')
    #处理post请求
    def post(self,request):
        #获取页面信息
        username=request.POST['username']
        password=request.POST['password']
        print('页面信息：',username,password)
        #用户信息写入数据库
        a=UserInfo.objects.create(
            username=username,password=password
        )
        print('信息写入数据库！！！')
        return render(request,'login.html')
#登录类
#自定义装饰器方法
def decoreate_login(func):
    def inner(request,*args,**kwargs):
        print('自定义装饰器被调用！！！')
        print('请求路径%s' % request.path)
        username=request.COOKIES.get('username')
        print('username:',username)
        return func(request,*args,**kwargs)
    return inner
#1.类外面 name属性
@method_decorator(decoreate_login,name='post')
class LoginView(View):
    #处理get请求
    def get(self,request):
        return render(request, './login.html')
    #处理post方法
    #类中，方法外 只对类中的某一个方法
    @method_decorator(decoreate_login)
    def post(self,request):
        username=request.POST.get('username')
        password=request.POST.get('password')
        #数据库用户名密码进行匹配
        data=UserInfo.objects.filter(username=username,
                                     password=password)
        if data:
            response=render(request,'suc.html',{
                'name':username,
                'password':password,
                'str':'登录成功！！！'
            })
            response.set_cookie('username',username,3600)
            return response
        else:
            return HttpResponse('登陆失败！！！')